package com.tang.usercenter.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tang.common.config.shiroConfig.JwtToken;
import com.tang.common.utils.JwtUtils;
import com.tang.common.utils.UserUtils;
import com.tang.usercenter.entity.UserEntity;
import com.tang.usercenter.mapper.UserMapper;
import com.tang.usercenter.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import java.security.SecureRandom;

@Service
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {
    @Override
    public UserEntity getCurrentUser() {
        String userName = UserUtils.getCurrentUserName();
        return getOne(new LambdaQueryWrapper<UserEntity>()
                .select(UserEntity::getId,UserEntity::getUserName,UserEntity::getPicture)
                .eq(UserEntity::getUserName,userName));
    }

    @Override
    public UserEntity getUserByUserName(String userName) {
        log.info("getUserByUserName: {}",userName);
        return getOne(new LambdaQueryWrapper<UserEntity>()
                .eq(UserEntity::getUserName,userName));
    }

    @Override
    public void register(UserEntity entity) {
        // 检查用户是否已存在
        if (getUserByUserName(entity.getUserName()) != null)throw new RuntimeException("用户已存在");

        // 生成盐值
        byte[] saltByte = new byte[16];
        new SecureRandom().nextBytes(saltByte);
        String salt = new String(saltByte);
        entity.setSalt(salt);

        // 对密码进行加密处理
        Md5Hash md5Hash = new Md5Hash(entity.getPassword(),salt);
        entity.setPassword(md5Hash.toHex());

        save(entity);
    }

    @Override
    public String login(UserEntity entity) {
        JwtToken token = new JwtToken(JwtUtils.encryptForToken(entity.getUserName(), entity.getPassword()));
        Subject subject = SecurityUtils.getSubject();
        subject.login(token);
        return (String) token.getPrincipal();
    }
}
